package com.lin.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class OnlineCountListener implements HttpSessionListener{
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext context = se.getSession().getServletContext();
        Integer onlineCount = (Integer) context.getAttribute("onlineCount");
        if (onlineCount == null) {
            onlineCount = 0;
        } else {
            onlineCount = onlineCount + 1;
        }
        context.setAttribute("onlineCount", onlineCount);
        System.out.println("current online count: " + onlineCount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext context = se.getSession().getServletContext();
        Integer onlineCount = (Integer) context.getAttribute("onlineCount");
        if (onlineCount == null) {
            onlineCount = 0;
        } else if (onlineCount == 0){
            onlineCount = 0;
        } else {
            onlineCount--;
        }
        context.setAttribute("onlineCount", onlineCount);
        System.out.println("current online count: " + onlineCount);
    }
}
